import java.util.ArrayList;
import java.util.List;

/**
* @description: 1592. 重新排列单词间的空格
* @author hewei
* @date 2022/9/7 14:01
* @version 1.0
*/

public class ReorderSpaces {

    public static void main(String[] args) {
        System.out.println(new ReorderSpaces().reorderSpaces("  this   is  a sentence "));
    }

    public String reorderSpaces(String text) {
        List<String> list = new ArrayList<>();
        int l = 0;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == ' ') {
                l = i + 1;
            } else if (i == text.length() - 1 || text.charAt(i + 1) == ' '){
                list.add(text.substring(l, i + 1));
            }
        }
        String[] split = list.toArray(new String[list.size()]);
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == ' ') ++count;
        }
        StringBuilder ans = new StringBuilder();
        if (split.length == 1) {
            ans.append(split[0]);
            for (int i = 0; i < count; i++) {
                ans.append(" ");
            }
        } else {
            int temp = count / (split.length - 1);
            ans.append(split[0]);
            for (int i = 1; i < split.length; i++) {
                for (int j = 0; j < temp; j++) {
                    ans.append(" ");
                }
                ans.append(split[i]);
            }
            for (int i = 0; i < count % (split.length - 1); i++) {
                ans.append(" ");
            }
        }
        return ans.toString();
    }
}
